// 获取用户频道异步action creator
import { http } from '@/utils/http'
import { RootThunkAction } from '@/types/store'
import {
  AllChannelsResponse,
  ArticlesResponse,
  Channel,
  ChannelResponse,
} from '@/types/data'
const CHANNEL_KEY = 'geek-channels'

export const getUserChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {
    const token = getState().login.token
    // const { login: { token } } = getState() // 解构定义写法
    // 1. 在该 action 中，进行数据获取的逻辑判断，判断条件是用户是否登录
    if (token) {
      // 2. 如果已登录，发送请求获取用户的频道列表数据
      const res = await http.get<ChannelResponse>('/user/channels')
      // console.log('/user/channels', res);
      dispatch({ type: '/home/getChannels', payload: res.data.data.channels })
    } else {
      // 3. 如果未登录，先判断本地缓存中有没有频道列表数据
      const localChannels = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) || '[]'
      ) as Channel[]
      // 3-1 如果本地没有，就发送请求获取默认的频道列表数据，并存储到本地缓存中
      if (localChannels.length === 0) {
        const res = await http.get<ChannelResponse>('/user/channels')
        localStorage.setItem(
          CHANNEL_KEY,
          JSON.stringify(res.data.data.channels)
        )
        // 未登录的情况下，redux中也存一份
        dispatch({
          type: '/home/getChannels',
          payload: res.data.data.channels,
        })
      } else {
        // 3-2. 如果本地有，拿到本地的频道列表数据
        // console.log('本地已有', localChannels)
        dispatch({ type: '/home/getChannels', payload: localChannels })
      }
    }
  }
}

// 获取剩余频道的异步 action creator
export const getRestChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {
    // 请求所有频道数据
    const res = await http.get<AllChannelsResponse>('channels')
    // 频道id
    const allChannels = res.data.data.channels
    // console.log('所有的用户频道', allChannels)
    // 用户频道
    const userChannels = getState().home.channels
    // console.log('我的频道', userChannels)
    // 剩余频道
    const restChannels = allChannels.filter(
      // 把id没有找到的过滤出来
      (item) => userChannels.findIndex((item2) => item.id === item2.id) < 0
    )
    // const restChannels = differenceBy(allChannels, userChannels, 'id')

    // 把数据存储到redux中
    dispatch({
      type: '/home/getRestChannel',
      payload: restChannels,
    })
  }
}

// 切换频道高亮
export const toggleChannel = (id: number): RootThunkAction => {
  return (dispatch) => {
    dispatch({ type: 'home/toggleChannel', payload: id })
  }
}

// 删除频道
export const delMyChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    const token = getState().login.token
    if (token) {
      // 登录用户
      await http.delete(`/user/channels/${channel.id}`)
    } else {
      // 未登录用户
      // 先取出本地数据
      const localChannels = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) || '[]'
      ) as Channel[]
      // 删除选中的频道
      const userChannel = localChannels.filter((item) => item.id !== channel.id)
      // 本地存储数据
      localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannel))
    }
    // 分发action，修改reducer 数据
    dispatch({ type: 'home/delMyChannel', payload: channel })
  }
}

// 添加我的频道
export const addChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    const token = getState().login.token
    if (token) {
      // 登录
      await http.patch('/user/channels', { channels: [channel] })
    } else {
      // 未登录
      const localChannels = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) || '[]'
      ) as Channel[]
      const userChannel = [...localChannels, channel]
      localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannel))
    }
    dispatch({ type: 'home/addChannel', payload: channel })
  }
}

// 请求频道数据的 异步 action creator
export const getArticleList = (
  channelId: number,
  timestamp: string | number | null
): RootThunkAction => {
  return async (dispatch) => {
    // 请求数据
    console.log('请求文章列表数据')
    const res = await http.get<ArticlesResponse>('/articles', {
      params: {
        channel_id: channelId,
        timestamp: timestamp,
      },
    })
    console.log('返回文章列表数据', res.data.data.results)
    // 分发action把数据交给reducer
    dispatch({
      type: 'home/getArticleList',
      payload: { channelId, articles: res.data.data },
    })
  }
}
